package pers.whj.util;

import java.io.*;

public class SerializationUtil {
    public static byte[] serialize(Serializable obj) throws Exception {
        byte[] result = null;
        if (obj != null) {
            try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos)) {
                oos.writeObject(obj);
                result = bos.toByteArray();
            } catch (IOException e) {
                throw new Exception(e);
            }
        }
        return result;
    }

    public static <T> T deserialize(byte[] data, Class<T> clazz) throws Exception {
        if (data != null) {
            try (ByteArrayInputStream bis = new ByteArrayInputStream(data); ObjectInputStream ois = new ObjectInputStream(bis)) {
                return clazz.cast(ois.readObject());
            } catch (IOException e) {
                throw new Exception(e);
            }
        }
        return null;
    }
}